package com.mhkj.workflow.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.mhkj.base.earlyWarning.entity.EarlyWarning;
import com.mhkj.base.earlyWarning.service.EarlyWarningService;
import com.mhkj.base.templete.entity.PlanTemplete;
import com.mhkj.base.templete.service.PlanTempleteService;
import com.mhkj.common.constant.Constants;
import com.mhkj.common.enums.MessageType;
import com.mhkj.common.enums.PlanSate;
import com.mhkj.common.util.HttpClientUtil;
import com.mhkj.execute.adjust.entity.PlanNodeAdjust;
import com.mhkj.execute.adjust.service.PlanNodeAdjustService;
import com.mhkj.execute.feedback.entity.PlanFeedBack;
import com.mhkj.execute.feedback.service.PlanFeedBackService;
import com.mhkj.execute.plan.entity.PlanNodeNew;
import com.mhkj.execute.plan.service.PlanNodeNewService;
import com.mhkj.revise.plan.entity.Plan;
import com.mhkj.revise.plan.entity.PlanNode;
import com.mhkj.revise.plan.service.PlanNodeService;
import com.mhkj.revise.plan.service.PlanService;
import com.mhkj.revise.professional.service.ProfessionalPlanNodeService;
import com.mhkj.workflow.dao.WorkFlowLoggerDao;
import com.mhkj.workflow.entity.WorkFlowLogger;
import com.mhkj.workflow.service.WorkFlowLoggerService;
import com.mics.core.common.util.DateUtils;
import com.mics.core.common.util.ftp.FtpUtil;
import com.mics.core.system.base.service.impl.BaseServiceImpl;
import com.mics.core.system.organizational.bean.Employee;
import com.mics.core.system.organizational.service.OrgService;
/**
 * 任务书services实现类
 * @author Administrator
 *
 */
@Service
@Transactional
public class WorkFlowLoggerServiceImpl extends BaseServiceImpl<WorkFlowLogger> implements WorkFlowLoggerService {


	@Resource
	private WorkFlowLoggerDao dao;
	
	public WorkFlowLoggerDao getDao() {
		return dao;
	}
	@Resource
	public void setDao(WorkFlowLoggerDao dao) {
		super.setBaseRepository(dao);
	}

	@Resource
	private WorkFlowLoggerService flowLoggerService;
	@Resource
	private PlanNodeNewService planNodeNewService;
	@Resource
	private PlanNodeService planNodeService;
	@Resource
	private PlanNodeAdjustService planNodeAdjustService;
	@Resource
	private PlanService planService;
	@Resource
	private PlanFeedBackService planFeedBackService;
	@Resource
	private ProfessionalPlanNodeService professionalPlanNodeService;
	
	@Resource
	private PlanTempleteService planTempleteService;
	@Autowired
	private OrgService orgService;

	@Resource
	private EarlyWarningService earlyWarningService;
	
	@Override
	public WorkFlowLogger getWorkFlowById(Long id) {
		// TODO Auto-generated method stub
		return dao.getWorkFlowById(id);
	}
	@Override
	public WorkFlowLogger getJumpUrlByProcInsId(String procInsId) {
		// TODO Auto-generated method stub
		return dao.getJumpUrlByProcInsId(procInsId);
	}
	
	@Override
	public List<WorkFlowLogger> getWorkFlowListForOk() {
		
		Specification<WorkFlowLogger> spec = new Specification<WorkFlowLogger>() {
			/**
			 * 序号
			 */
			private static final long serialVersionUID = 306602690902191635L;

			@Override
			public Predicate toPredicate(Root<WorkFlowLogger> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				List<Predicate> lstPredicates = new ArrayList<Predicate>();
				Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
				Predicate ongoing = criteriaBuilder.equal(root.get("status").as(String.class), "ongoing");
				Predicate no = criteriaBuilder.equal(root.get("status").as(String.class), "1");

				lstPredicates.add(criteriaBuilder.or(ongoing, no));

				return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
			}
		};
		
		return dao.findAll(spec);
	}
	/**
	 * 获取当前流程状态 更改业务逻辑状态
	 */
	@Override
	public String getActivityState(List<WorkFlowLogger> list) throws IOException {
		
		String message=null;
	    for (int i = 0; i < list.size(); i++) {
		    Long id=list.get(i).getId();
		    String procInsId= list.get(i).getProcInsId();
		    Properties properties = new Properties();
			properties.load(FtpUtil.class.getResourceAsStream("/workflow.properties"));
			String url=properties.get("url").toString()+"/act/taskApi/getActivityState";
			Map<String,String> map = new HashMap<>();
			map.put("procInsId", procInsId);//流程实例ID
			message=HttpClientUtil.post(url, map);
			JSONObject jsStr = JSONObject.parseObject(message);

			String respCode=jsStr.get("respCode").toString();//获取返回的状态
			if(respCode.equals("1")) {
				String data=jsStr.get("data").toString();
				String activityState=JSONObject.parseObject(data).get("activityState").toString();
				WorkFlowLogger logger=flowLoggerService.getById(id);
				logger.setStatus(activityState);//设置流程状态
				
				message=flowLoggerService.edit(logger);
				if(message.equals("ok")) {
					//ProjectBudget projectBudget=projectBudgetService.getById(Long.parseLong(logger.getExampleId()));
					int status=0;
					if(logger.getStatus().equals("ongoing")) {
						status=1;
					}else if(logger.getStatus().equals("successful")) {
						status=2;
					}else if(logger.getStatus().equals("failure")) {
						status=3;
					}
					
					
					String entityName=list.get(i).getExampleEntity();
					if(entityName.equals("planNodeNew")){
						PlanNodeNew planNodeNew= planNodeNewService.getById(list.get(i).getExampleId());
						if(planNodeNew.getAuditState()!=2) {
							planNodeNew.setAuditState(status);
							planNodeNewService.edit(planNodeNew);
							
							
							if(status==2) {
								PlanNode planNode = new PlanNode();
								planNode.setNodeName(planNodeNew.getNodeName());
								planNode.setBeginDate(planNodeNew.getBeginDate());
								planNode.setEndDate(planNodeNew.getEndDate());
								planNode.setBusiModel(planNodeNew.getBusiModel());
								planNode.setCompanyId(planNodeNew.getCompanyId());
								planNode.setCompleteStandard(planNodeNew.getCompleteStandard());
								planNode.setDeadline(planNodeNew.getDeadline());
								planNode.setOfficeId(planNodeNew.getOfficeId());
								planNode.setPostId(planNodeNew.getPostId());
								planNode.setBusiness(planNodeNew.getBusiness());
								planNode.setNodeProperty(planNodeNew.getNodeProperty());
								planNode.setPlan(planNodeNew.getPlan());
								planNode.setRemark(planNodeNew.getRemark());
								planNodeService.save(planNode);
								if(!StringUtils.isEmpty(planNodeNew.getCooperatePostPerson())) {
									

									Employee employee = orgService.employeeInfo(planNodeNew.getCooperatePostPerson());//获取用户信息

									PlanNode planNode1 = new PlanNode();
									planNode1.setNodeName(planNodeNew.getNodeName());
									planNode1.setBeginDate(planNodeNew.getCooperateBeginDate());
									planNode1.setEndDate(planNodeNew.getCooperateEndDate());
									planNode1.setBusiModel(planNodeNew.getBusiModel());
									planNode1.setCompanyId(employee.getCompanyid());
									planNode1.setCompleteStandard(planNodeNew.getCompleteStandard());
									planNode1.setDeadline(planNodeNew.getDeadline());
									planNode1.setOfficeId(employee.getOffice().getId());
									planNode1.setPostId(employee.getRoleList().get(0).getId());
									planNode1.setBusiness(planNodeNew.getBusiness());
									planNode1.setNodeProperty(planNodeNew.getNodeProperty());
									planNode1.setPlan(planNodeNew.getPlan());
									planNode1.setRemark(planNodeNew.getRemark());
									planNodeService.save(planNode1);
									
								}
							}
						}
						
					}else if(entityName.equals("planNodeAdjust")){
						PlanNodeAdjust planNodeAdjust = planNodeAdjustService.getById(list.get(i).getExampleId());

						if(planNodeAdjust.getAuditState()!=2) {
							planNodeAdjust.setAuditState(status);
							planNodeAdjustService.edit(planNodeAdjust);
							int overdueDay=0;
							
							if(status==2) {
								PlanNode planNode1 = planNodeService.getById(planNodeAdjust.getPlanNode().getId());
								List<PlanNode> planNodelist = professionalPlanNodeService.getSameNameNode(planNode1.getId());// 获取关键，主项，专项 节点数据
								Date now = DateUtils.getDateYMD(new Date(), "yyyy-MM-dd");
								for (PlanNode planNode : planNodelist) {
									if(planNodeAdjust.getAdjustType().getCode().equals("100047")) {//节点延迟
										planNode.setDelayNum(planNode.getDelayNum()+1);
										planNode.setDelayDate(planNodeAdjust.getDelayDate());
										planNode.setDelayDay(planNodeAdjust.getAdjustDeadline());

										overdueDay = DateUtils.compareDay(now, DateUtils.addDay(planNode.getEndDate(), planNodeAdjust.getAdjustDeadline()));
										if(overdueDay > 0 ) {
											planNode.setOverDay(overdueDay);
										}else {
											planNode.setOverDay(0);
										}
										planNodeService.edit(planNode);
										
										if(planNode.getOverDay() > Constants.DELAY){//失控
											planNode.setRiskState(2);
											professionalPlanNodeService.edit(planNode);
										}else {
											 overdueDay = DateUtils.compareDay(now, DateUtils.addDay(planNode.getEndDate(), planNode.getDelayDay()));
											if(overdueDay > 0 && (planNode.getState() == PlanSate.running.getState() || planNode.getState() == PlanSate.overdue.getState() )){  //逾期
												planNode.setRiskState(1);
												planNode.setState(PlanSate.overdue.getState());
												professionalPlanNodeService.edit(planNode);
											}else {
												List<EarlyWarning> earlyWarnings = earlyWarningService.findAll(); 
												for(EarlyWarning earlyWarning : earlyWarnings){
													int useDay = DateUtils.compareDay(now, planNode.getBeginDate());
													int deadlineRate = useDay / planNode.getDeadline()*100;
													if(deadlineRate >= earlyWarning.getWorkDayLeast() && deadlineRate < earlyWarning.getWorkDayMax() && planNode.getRate() < earlyWarning.getSchedule()){//风险
														planNode.setRiskState(1);
														professionalPlanNodeService.edit(planNode);
													}else {
														planNode.setRiskState(0);
														planNode.setState(PlanSate.running.getState());
														professionalPlanNodeService.edit(planNode);
													}
												}
											}
										}	
									}else if(planNodeAdjust.getAdjustType().getCode().equals("100048")) {//节点暂停
										planNode.setState(8);
									/*	planNode.setBeginDate(planNodeAdjust.getAdjustBeginDate());
										planNode.setEndDate(planNodeAdjust.getAdjustEndDate());*/
										planNode.setRiskState(0);//风险设置为0
										planNodeService.edit(planNode);
										
									}else if(planNodeAdjust.getAdjustType().getCode().equals("100049")) {//节点取消
										planNode.setState(9);
										planNode.setRiskState(0);//风险设置为0
										planNodeService.edit(planNode);
									}
									
									
									
								}
								
							}
						}
						
					}else if(entityName.equals("plan")){//计划审批
						Plan plan = planService.getById(list.get(i).getExampleId());

						if(plan.getState()!=2) {
							plan.setState(status);
							planService.edit(plan);
						}
						
					}else if(entityName.equals("planTemplete")){//计划模板审批
						PlanTemplete planTemplete = planTempleteService.getById(list.get(i).getExampleId());

						if(planTemplete.getState()!=2) {
							planTemplete.setState(status);
							planTempleteService.edit(planTemplete);
						}
						
					}else if(entityName.equals("planNode")){//进度填报 
						PlanFeedBack planFeedBack =planFeedBackService.getById(list.get(i).getExampleId());
						PlanNode planNode = planNodeService.getById(planFeedBack.getPlanNode().getId());
						if(planNode.getAduitState()!=2) {
							planNode.setAduitState(status);
							if(planNode.getRiskState()!=0) {
								planNode.setRiskState(0);
							}
							if(planNode.getAduitState()==3) {
								planFeedBack.setCompleteIns("被驳回");
								planFeedBackService.edit(planFeedBack);
							}else if(planNode.getAduitState()==2) {
								
								int state=planNode.getState();
								if(state==7) {//如果逾期 修改状态为6 逾期完成
									planNode.setState(6);
								}else {//其他 已完成
									planNode.setState(5);
								}
								planNode.setRate(100);
								planNode.setCompleteDate(planFeedBack.getOverDate());
							}
							
							planNodeService.edit(planNode);
						}
						
					}
					/*if(projectBudget.getId()>0) {
						projectBudget.setStatus(status);//设置状态
						projectBudgetService.save(projectBudget);
					}*/
				}
			}
	    }
		// TODO Auto-generated method stub
		return message;
	}
}
